package com.lhkj.ct.meta.modules.gauge.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.lhkj.ct.base.enums.DeleteStatus;
import com.lhkj.ct.base.model.dto.PageQuery;
import com.lhkj.ct.base.mybatis.core.metadata.SqlOrder;
import com.lhkj.ct.base.mybatis.extension.service.impl.IServiceImpl;
import com.lhkj.ct.base.utils.ShiroUtil;
import com.lhkj.ct.base.utils.Validate;
import com.lhkj.ct.meta.modules.gauge.common.enums.GaugeType;
import com.lhkj.ct.meta.modules.gauge.mapper.QnrMapper;
import com.lhkj.ct.meta.modules.gauge.model.entity.TblGaugeQuestion;
import com.lhkj.ct.meta.modules.gauge.model.entity.TblQnr;
import com.lhkj.ct.meta.modules.gauge.model.vo.QnrPageVo;
import com.lhkj.ct.meta.modules.gauge.service.GaugeQuestionService;
import com.lhkj.ct.meta.modules.gauge.service.QnrConfigService;
import com.lhkj.ct.meta.modules.recycle.common.constant.RecycleType;
import com.lhkj.ct.meta.modules.recycle.entity.TblRecycleBin;
import com.lhkj.ct.meta.modules.recycle.service.RecycleBinService;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 调查问卷 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2023-10-26
 */
@Service
public class QnrConfigServiceImpl extends IServiceImpl<QnrMapper, TblQnr> implements QnrConfigService {

    @Resource
    private RecycleBinService recycleBinService;

    @Resource
    private GaugeQuestionService questionService;

    @Override
    public IPage<QnrPageVo> selectQnrPage(TblQnr qnr, PageQuery pageQuery) {
        Page<TblQnr> page = generatePage(pageQuery, SqlOrder.desc(TblQnr::getCreateTime, "t"));
        return getBaseMapper().selectQnrPage(page, qnr, pageQuery);
    }

    @Override
    public TblQnr getForm(String id) {
        return getBaseMapper().getForm(id);
    }

    @Override
    public List<Map<String, List<Map<String, Object>>>> groupByCategory(TblQnr qnr) {
        return getBaseMapper().groupByCategory(qnr);
    }

    @Override
    public boolean updateStatus(Integer status, List<String> ids) {
        return SqlHelper.retBool(getBaseMapper().update(null,
                new LambdaUpdateWrapper<TblQnr>()
                        .in(TblQnr::getId, ids)
                        .set(TblQnr::getStatus, status)
                        .eq(status == 1, TblQnr::getStatus, 0)
                        .eq(status == 2, TblQnr::getStatus, 1)
        ));
    }

    @SuppressWarnings("unchecked")
    @Override
    public int removeByIds(Collection<? extends Serializable> idList) {
        final QnrConfigService currentProxy = (QnrConfigService) AopContext.currentProxy();
        return recycleBinService.logicDelete((List<String>) idList, currentProxy::logicDelete);
    }

    @Override
    public int logicDelete(String id) {
        TblQnr target = getBaseMapper().selectById(id);
        if (null == target) return 0;
        return recycleBinService.logicDeleteRealSource(
                getBaseMapper(),
                id,
                TblQnr::getId,
                TblQnr::getDelFlag,
                DeleteStatus.DELETED,
                TblRecycleBin.builder().sourceId(id).title(target.getQnrName()).sourceType(RecycleType.QUESTIONNAIRE).build());
    }

    @Override
    public void copy(String id) {
        TblQnr target = getBaseMapper().selectById(id);
        Validate.notNull(target, "问卷不存在或已删除！");
        int version = Optional.ofNullable(target.getVNum()).orElse(1);
        getBaseMapper().update(new LambdaUpdateWrapper<TblQnr>()
                .set(TblQnr::getVNum, version + 1)
                .eq(TblQnr::getId, id)
        );
        target.setQnrName(String.format("%s(%d)", target.getQnrName(), version));
        target.setVNum(1);
        target.setCreateBy(ShiroUtil.getAuthUserOfNullAble().getUserId());
        target.setCreateTime(LocalDateTime.now());
        target.setUpdateBy(null);
        target.setUpdateTime(null);
        target.setStatus(0);
        target.setId(null);
        getBaseMapper().insert(target);
        List<TblGaugeQuestion> tblGaugeQuestions = questionService.selectQutWithOptWithLogicByGaugeId(id, GaugeType.QUESTIONNAIRE)
                .stream().peek(p -> {
                    p.setQutId(null);
                    p.setGaugeId(target.getId());
                }).collect(Collectors.toList());
        questionService.saveBatch(tblGaugeQuestions);
    }
}
